<template>
  <div class="main">
    <Search :initData="initSearchData" @emitSearchData="getSearchData"></Search>
    <div class="content">
      <a-row :gutter="[16, 16]" style="position: relative;">
        <Pie :span="24" :pieData="pieOfAfterSaleByDepartment"></Pie>
        <DepartmentLists
          :departmentLists="pieOfAfterSaleByDepartmentLists"
        ></DepartmentLists>
      </a-row>
      <a-row :gutter="[16, 16]">
        <BarChart :span="12" :barData="histogramOfAfterSaleByMonth"></BarChart>
        <Ranking :span="12" :rankingData="rankingData"></Ranking>
      </a-row>
    </div>
  </div>
</template>

<script>
import Pie from "@/components/echart/pie";
import BarChart from "@/components/echart/bar";
import Search from "./components/search";
import DepartmentLists from "./components/departmentLists";
import Ranking from "./components/ranking";
import { buildDateAxis } from "@/unit/tool";
import api from "@/server/userConfig";

function transformTimeArray(lists, type) {
  return lists.map((item, index) => {
    if (type == "已完成") {
      // return 3;
      return {
        value: [item.time, item.over]
      };
    } else {
      // return 1;
      return {
        value: [item.time, item.notOver]
      };
    }
  });
}

function buildPieData(pieDataLists, titleStr) {
  let lists = [{ option: {}, data: [] }];
  let dataLists = [];

  pieDataLists.forEach((item, index) => {
    dataLists.push({
      name: item.secondDepartment,
      value: item.number
    });
  });

  dataLists = dataLists.sort((a, b) => {
    return b.value - a.value;
  });

  // legendData = dataLists.map((item, index) => {
  //   let name = item.name;
  //   selected[name] = index < showCount ? true : false;
  //   return name;
  // });

  lists[0].option = {
    radius: ["60", "120"],
    center: ["540", "180"],
    label: {
      position: "outside",
      formatter: function(e) {
        return `${e.name}  ${Math.ceil(parseFloat(e.percent))}%`;
      }
    }
  };

  lists[0].data = dataLists;
  return {
    title: {
      text: titleStr,
      left: "44",
      top: "24",
      textStyle: {
        fontSize: 18,
        fontWeight: 600,
        color: "#1890FF"
      }
    },
    legend: {
      data: []
    },
    dataLists: lists
  };
}

function buildBarLists(barDataLists, option) {
  let { startTime, endTime, timeFormat } = option;
  let dataLists = [];
  let stateLists = ["已完成", "未完成"];

  let xAxisData = buildDateAxis({ timeFormat, startTime, endTime });

  stateLists.forEach((typeStr, index) => {
    dataLists.push({
      option: {
        name: typeStr
      },
      data: transformTimeArray(barDataLists, typeStr)
    });
  });

  return {
    title: {
      text: "工单分布",
      left: "44",
      top: "24",
      textStyle: {
        fontSize: 18,
        fontWeight: 600,
        color: "#1890FF"
      }
    },
    legend: {
      orient: "horizontal",
      left: "center",
      bottom: "10"
    },
    grid: { left: "60", top: "80", width: "720" },
    xAxisData,
    lists: dataLists
  };
}

export default {
  name: "ServiceStatistics",
  components: {
    Search,
    Pie,
    DepartmentLists,
    BarChart,
    Ranking
  },
  data() {
    let moment = this.$Moment;
    return {
      initSearchData: {
        timeType: "最近一年",
        startTime: `${moment()
          .month(moment().month() - 11)
          .startOf("month")
          .format("YYYY-MM-DD")} 00:00:00`,
        endTime: `${moment()
          .month(moment().month() - 0)
          .endOf("month")
          .format("YYYY-MM-DD")} 23:59:59`
      },
      pieOfAfterSaleByDepartment: {},
      pieOfAfterSaleByDepartmentLists: [],
      histogramOfAfterSaleByMonth: {},
      rankingData: {}
    };
  },
  methods: {
    async getPieOfAfterSaleByDepartment(parames, key) {
      const res = await api.getPieOfAfterSaleByDepartment({
        startTime: parames.startTime,
        endTime: parames.endTime,
        statisticsType: parames.statisticsType
      });
      console.log(res);

      if (res.MsgCode !== 0) {
        this.$message.error(`数据查询异常`);
        return;
      }

      this[key] = buildPieData(res.Data.content, "部门数据统计");

      let lists = res.Data.content;
      lists = lists.sort((a, b) => {
        return b.number - a.number;
      });
      this[key + "Lists"] = lists;
    },

    async getHistogramOfAfterSaleByMonth(parames, key) {
      const res = await api.getHistogramOfAfterSaleByMonth({
        startTime: parames.startTime,
        endTime: parames.endTime,
        statisticsType: parames.statisticsType
      });
      console.log(res);

      if (res.MsgCode !== 0) {
        this.$message.error(`数据查询异常`);
        return;
      }

      this[key] = buildBarLists(res.Data, {
        startTime: parames.startTime,
        endTime: parames.endTime,
        timeFormat: "months"
      });
    },

    getData(parames) {
      this.getPieOfAfterSaleByDepartment(
        {
          startTime: parames.startTime,
          endTime: parames.endTime,
          statisticsType: parames.timeType
        },
        "pieOfAfterSaleByDepartment"
      );
      this.getHistogramOfAfterSaleByMonth(
        {
          startTime: parames.startTime,
          endTime: parames.endTime,
          statisticsType: parames.timeType
        },
        "histogramOfAfterSaleByMonth"
      );
      this.rankingData = parames;
    },
    getSearchData(value) {
      this.getData(value);
    },
    getLocalStorageData() {
      const phone = localStorage.getItem("phone");
      this.userName = phone;
      if (!phone) {
        this.$router.push("/");
      }
    },
    callback(key) {}
  },
  created() {
    this.getLocalStorageData();
  },
  mounted() {
    console.log(this.initSearchData);
    this.getData(this.initSearchData);
  }
};
</script>

<style scoped="scoped">
.main {
  height: 100%;
  width: 100%;
  padding: 0px 0px 0px 0px;
}

.main > .content {
  padding: 16px;
  background: #ecf2f7;
}
</style>
